<?php

namespace App\Models;

use App\Enums\OrderState;
use App\Events\OrderPaidEvent;
use App\Models\Traits\BelongsToApplication;
use App\Models\Traits\BelongsToPlayer;
use App\Models\Traits\BelongsToUser;
use App\Traits\AutoCreateOrderNo;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Order extends Model
{
    use AutoCreateOrderNo,
        BelongsToApplication,
        BelongsToUser,
        BelongsToPlayer;

    protected $casts = [
        'state' => OrderState::class,
        'paid_at' => 'datetime',
        'resource' => 'json',
    ];

    protected static function boot(): void
    {
        parent::boot();

        self::creating(function (Order $order) {
            $order->state = OrderState::INIT;
        });
    }

    public function wechat(): BelongsTo
    {
        return $this->belongsTo(Wechat::class);
    }

    public function payment(): BelongsTo
    {
        return $this->belongsTo(Payment::class);
    }

    public function refunds(): HasMany
    {
        return $this->hasMany(Refund::class);
    }

    public function season(): BelongsTo
    {
        return $this->belongsTo(Season::class);
    }

    public function chapter(): BelongsTo
    {
        return $this->belongsTo(Chapter::class);
    }

    public function player(): BelongsTo
    {
        return $this->belongsTo(Player::class);
    }

    public function gift(): BelongsTo
    {
        return $this->belongsTo(Gift::class);
    }

    /**
     * Notes   : 支付成功操作
     *
     * @Date   : 2024/7/18 下午5:42
     * @Author : <Jason.C>
     * @param  array  $resource
     */
    public function paid(array $resource): void
    {
        $this->paid_at = now();
        $this->state = OrderState::PAID;
        $this->resource = $resource;
        $this->save();

        OrderPaidEvent::dispatch($this);
    }
}
